//=========================================
//依赖 import Shape.js
//依赖 improt Vector-build.js
//依赖 import Projection.js
//=========================================

/**
 * 多边形类
 */
function Polygon () {
    this.points = [];
}

// Polygon.prototype = new Shape(); //依赖于Shape.js
Polygon.prototype = (function (o) {
    var s = new Shape();
    for(var p in o) {
        s[p] = o[p];
    }
    return s;
})({
    /**
     * 重写碰撞检查调用
     */
    collidesWith: function (shape) {
        // var axes = shape.getAxes();
        // if(axes === undefined) {
        //     // shape 是圆形
        //     return polygonCollidesWithCircle(this, shape);
        // } else {
        //     // shape 多边形
        //     axes.concat(this.getAxes());
        //     return !this.separationOnAxes(axes, shape);
        // }
        
        //加入最小平移向量后
        if(shape.radius !== undefined) {
            return polygonCollidesWithCircle(this, shape);
        } else {
            return polygonCollidesWithPolygon(this, shape);
        }
    },
    
    /**
     * 获取投影对象
     * @param {VectorB} 投影轴
     * @return {Projection} 投影对象
     */
    project: function (axis) {
        var scalars = [],
            v = new VectorB();
        this.points.forEach(function (point) {
            v.x = point.x;
            v.y = point.y;
            scalars.push(v.dotProduct(axis));
        });
        return new Projection(Math.min.apply(Math, scalars), Math.max.apply(Math, scalars));
    },
    
    /**
     * 获取当前多边形所有投影轴
     * 即：获取每一条边的单位法向量
     */
    getAxes: function () {
        var v1 = new VectorB(),
            v2 = new VectorB(),
            axes = [];
        for(var i = 0; i < this.points.length - 1; i += 1) {
            v1.x = this.points[i].x;
            v1.y = this.points[i].y;

            v2.x = this.points[i+1].x;
            v2.y = this.points[i+1].y;
            axes.push(v1.edge(v2).normal()); 
        }

        v1.x = this.points[this.points.length - 1].x;
        v1.y = this.points[this.points.length - 1].y;

        v2.x = this.points[0].x;
        v2.y = this.points[0].y;
        axes.push(v1.edge(v2).normal());
        return axes;
    },

    /**
     * 添加新顶点
     * @param {Number} x 新顶点x坐标
     * @param {Number} y 新顶点y坐标
     */
    addPoint: function (x, y) {
        this.points.push(new Point(x, y));
    },

    /**
     * 绘制路径
     */
    createPath: function (ctx) {
        if(this.points.length === 0) return;
        ctx.beginPath();
        ctx.moveTo(this.points[0].x, this.points[0].y);
        for(var i = 0; i < this.points.length; i += 1) {
            ctx.lineTo(this.points[i].x, this.points[i].y);
        }
        ctx.closePath();
    },

    /**
     * 位移
     * @param {Number} dx x坐标位移量
     * @param {Number} dy y坐标位移量
     */
    move: function (dx, dy) {
        for(var i = 0; i < this.points.length; i += 1) {
            var point = this.points[i];
            point.x += dx;
            point.y += dy;
        }
    }
})